package com.huynv.ochuvietnam;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import com.huynv.ochuvietnam.KeyboardViewInterface;
import com.huynv.ochuvietnam.R;
import com.huynv.ochuvietnam.KeyboardView;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout.LayoutParams;

public class Game extends Activity implements OnTouchListener, KeyboardViewInterface {
	textAdapter gridAdapter;
	GridView gridview;
	TextView[] thumb=new TextView[36];
	TextView description;
	private int width;
	item[] ochubasic;
	private int height;
	KeyboardView keyboardView;
	private TextView keyboardOverlay;
	public static final float 	KEYBOARD_OVERLAY_OFFSET = 90;
	private boolean			downIsPlayable;	// false si le joueur à appuyé sur une case noire 
	private int 			downPos;		// Position ou le joueur à appuyé
    private int 			downX;			// Ligne ou le joueur à appuyé
    private int 			downY;			// Colonne ou le joueur à appuyé
	private int 			currentPos;		// Position actuelle du curseur
	private int 			currentX;		// Colonne actuelle du curseur
	private int 			currentY;		// Ligne actuelle du curseur
	//private Word			currentWord;	// Mot actuellement selectionné
	private boolean 		horizontal;		// Sens de la selection
	private ArrayList<View>	selectedArea = new ArrayList<View>(); 
	//item[] itemOchu;
	oChu OC;
	@Override
	protected void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);			
		setContentView(R.layout.game);
		gridview = (GridView) findViewById(R.id.gridview);
		gridview.setVisibility(View.VISIBLE);
		OC=new oChu();
		OC.getOChu();
		//itemOchu=OC.Result;
		this.width =OC.getCols();// this.gridview.getWidth();rows and cols so colunm se tinh o day
		this.height =OC.getRows();// this.gridview.getHeight();
		Log.e("hhhhhhhhhhhhhhhhhhhhhhhhhhhh", String.valueOf(this.width)+"_"+String.valueOf(this.height));
//		for(int i=0;i<this.width;i++){
//			for(int j=0;j<this.height;j++){
//				
//			}
//		}
		Display display = getWindowManager().getDefaultDisplay();
	    int kheight = display.getHeight();
	    int keyboardHeight = (int)(kheight / 4.4);
	    thumb=new TextView[this.width*this.height];
		gridview.setOnTouchListener(this);
		gridview.setNumColumns(this.width);
		android.view.ViewGroup.LayoutParams gridParams = this.gridview.getLayoutParams();
		gridview.setLayoutParams(gridParams);
		gridview.setVerticalScrollBarEnabled(false);
//		ochubasic=new item[OC.count];
//		ochubasic=OC.Result;
//		for(int j=0;j<OC.count;j++) ochubasic[j].keyword="";
		gridAdapter=new textAdapter(this,this.getApplicationContext(),thumb,this.width,this.height,OC.Result,OC.count);
		gridview.setAdapter(gridAdapter);
	    gridview.setOnItemClickListener(new OnItemClickListener() {
	//        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
	//            Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show();
	//        }
				@Override
				public void onItemClick(AdapterView<?> parent,
						View view, int position, long id) {
					// TODO Auto-generated method stub
					
				}
	    });
	    this.keyboardView = (KeyboardView)findViewById(R.id.keyboard);
        this.keyboardView.setDelegate(this);
        android.view.ViewGroup.LayoutParams KeyboardParams = this.keyboardView.getLayoutParams();
        KeyboardParams.height = keyboardHeight;
        this.keyboardView.setLayoutParams(KeyboardParams);
        this.keyboardOverlay = (TextView)findViewById(R.id.keyboard_overlay);
        this.description = (TextView)findViewById(R.id.description);
        
	}
	private void clearSelection() {
    	for (View selected: selectedArea)
    		selected.setBackgroundResource(R.drawable.area_empty);
    	selectedArea.clear();
	}
	@Override
	public boolean onTouch(View v, MotionEvent event)
	{
		switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
            {
            	int position = this.gridview.pointToPosition((int)event.getX(), (int)event.getY());
            	View child = this.gridview.getChildAt(position);

            	// Si pas de mot sur cette case (= case noire), aucun traitement
            	if (child == null) {
            		//if (this.solidSelection == false) {
                        clearSelection();
                    	this.gridAdapter.notifyDataSetChanged();
            		//}
            			
            		this.downIsPlayable = false;
            		return true;
            	}
        		this.downIsPlayable = true;

            	// Stocke les coordonnees d'appuie sur l'ecran
            	this.downPos = position;
                this.downX = this.downPos / this.width;
                this.downY = this.downPos % this.width;
                System.out.println("ACTION_DOWN, x:" + this.downX + ", y:" + this.downY + ", position: " + this.downPos);

                clearSelection();
                
            	// Colore la case en bleu
            	child.setBackgroundResource(R.drawable.area_selected);
            	selectedArea.add(child);

            	this.gridAdapter.notifyDataSetChanged();
        		break;
            }

            case MotionEvent.ACTION_UP:
            {
            	// Si le joueur à appuyé sur une case noire, aucun traitement 
            	if (this.downIsPlayable == false)
            		return true;
            	
                int position = this.gridview.pointToPosition((int)event.getX(), (int)event.getY());
                int x = position / this.width;
                int y = position % this.width;
                System.out.println("ACTION_DOWN, x:" + x + ", y:" + y + ", position: " + position);

            	// Si clique sur la case, inversion horizontale <> verticale
                // Si clique sur une autre case (= mouvement) calcul en fonction de la gesture
            	if (this.downPos == position && this.currentPos == position)
            	{
            		this.horizontal = !this.horizontal;
            	}
            	else if (this.downPos != position) 
            	{
            		this.horizontal = (Math.abs(this.downX - x) > Math.abs(this.downY - y));
            	}

            	// Test si un mot se trouve sur cette case
//                this.currentWord = getWord(this.downX, this.downY, this.horizontal);
//        	    if (this.currentWord == null)
//        	    	break;
        	    
        	    // Force la direction a etre dans le meme sens que le mot
        	    //this.horizontal = this.currentWord.getHorizontal();
                
            	// Si clique sur la case, place le curseur sur le mot
                // Sinon place le curseur au debut du mot
            	if (this.downPos == position)
            	{
            	    this.currentX = this.downX;
                    this.currentY = this.downY;
                	this.currentPos = position;
            	}
            	else
            	{
            	    //this.currentX = this.currentWord.getX();
                    //this.currentY = this.currentWord.getY();
                	//this.currentPos = this.currentY * this.width + this.currentX;
            	}

            	//this.txtDescription.setText(this.currentWord.getDescription());
            	this.description.setText(this.gridAdapter.getQuestionNow(this.downX,this.downY));
        		//Log.e("description "+this.gridAdapter.getQuestionNow(),"");
        	    // Set background color
//        	    

        	    this.gridAdapter.notifyDataSetChanged();
        	    break;
            }
        }
        // if you return false, these actions will not be recorded
        return true;
       
	}
	@Override
	public void onKeyDown(String value, int location[], int width) {
		Log.e("onKeyDown", value);	
		
		if (value.equals(" ") == false) {
			int offsetX = (this.keyboardOverlay.getWidth() - width) / 2;
			int offsetY = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, KEYBOARD_OVERLAY_OFFSET, getResources().getDisplayMetrics());
			FrameLayout.LayoutParams lp = (LayoutParams)this.keyboardOverlay.getLayoutParams();
			lp.leftMargin = location[0] - offsetX;
			lp.topMargin = location[1] - offsetY;
			this.keyboardOverlay.setLayoutParams(lp);
			this.keyboardOverlay.setText(value);
			this.keyboardOverlay.clearAnimation();
			this.keyboardOverlay.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void onKeyUp(String value) {
		//System.out.println("onKeyUp: " + value + ", insert in: " + currentX + "x" + currentY);
		Log.e("onKeyUp", value);		
		System.out.println("onKeyUp: " + value + ", insert in: " + currentX + "x" + currentY);

		// Efface l'overlay du clavier
		if (value.equals(" ") == false) {
			this.keyboardOverlay.setAnimation(AnimationUtils.loadAnimation(this, R.anim.keyboard_overlay_fade_out));
			this.keyboardOverlay.setVisibility(View.INVISIBLE);
		}

		// Si aucun mot selectionne, retour
//		if (this.currentWord == null)
//			return;

		// Case actuelle
		int x = this.currentX;
		int y = this.currentY;

		// Si la case est noire => retour
//		if (this.gridAdapter.isBlock(x, y))
//			return;
		
		// Ecrit la lettre sur le "curseur"
		this.gridAdapter.setTextOnXy(x, y,0, value);
		Log.e("Thay doi gia tri moi la "+value,"");
		this.gridAdapter.notifyDataSetChanged();
		Log.e("notifyDataSetChanged"+value,"");
//		this.description.setText(this.gridAdapter.getQuestionNow());
//		Log.e("description "+this.gridAdapter.getQuestionNow(),"");
		// Deplace sur le "curseur" sur la case precendante (effacer), ou suivante (lettres)
//		if (value.equals(" ")) {
//			x = (this.horizontal ? x - 1 : x);
//			y = (this.horizontal ? y: y - 1);
//		}
//		else
//		{
//			x = (this.horizontal ? x + 1 : x);
//			y = (this.horizontal ? y: y + 1);
//		}
//		
//		// Chuyển sang ô kế tiếp
		if (value!="") y=y+1;
		if (x >= 0 && x < this.height
				&& y >= 0 && y < this.width
				&& this.gridAdapter.isBlock(x, y) == false) {
			this.gridview.getChildAt(x * this.width + y).setBackgroundResource(R.drawable.area_current);
			this.gridview.getChildAt(this.currentX * this.width + this.currentY).setBackgroundResource(R.drawable.area_selected);
			this.currentX = x;
			this.currentY = y;
		}
//		this.currentX = x;
//        this.currentY = y;
	}
	
	@Override
	public void setDraft(boolean value) {
		//this.gridAdapter.setDraft(value);
	}
}
